<?php
/**
 * @author Artur Bier <izatop@gmail.com>
 * @package Application.View
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
/**
 * Pager
 */
class Pager extends ApplicationController implements IViewable
{
    protected $namespace    = 'Pager';
    
    private $count          = 0;
    private $page           = 1;
    private $pages          = 1;
    private $limit          = 30;
    private $start          = 0;
    private $view;
    
    public function __construct($count, $page = null, $limit = null)
    {
        $this->view = Registry::get('View');
        
        $this->count = $count;
        $this->page = ($page ? $page : Env::request('page', $this->page));
        $this->limit = ($limit ? $limit : $this->limit);
        
        $this->configure();
    }
    
    public function count()
    {
	return $this->count;
    }
    
    public function configure()
    {
        $this->pages = ceil($this->count / $this->limit);
       
        if ($this->page > $this->pages) {
            $this->page = $this->pages;
        }
        if ($this->page < 1) {
            $this->page = 1;
        }
         
        if($this->page > 1) {
            $this->start = ($this->page - 1)*$this->limit;
        }
    }
    
    public function getPageNumber()
    {
        return $this->page;
    }
    
    public function getStartNumber()
    {
        return $this->start;
    }
    
    public function getLimit()
    {
        return $this->limit;
    }
    
    public function getPages()
    {
        return $this->pages;
    }
    
    public function display()
    {
        return $this->view->fetch('Pager.tpl', true);
    }
    
    public function limit()
    {
        return $this->limit;
    }
    
    public function position()
    {
        return $this->start;
    }
    
    protected $prefix = '';
    
    public function setUrlPrefix($prefix)
    {
        $this->prefix = $prefix;
    }
    
    public function getQueryString(array $params = array())
    {
        $url = parse_url(Env::server('REQUEST_URI'));
        $query = array();
        if(array_key_exists('query', $url)) {
            parse_str($url['query'], $query);
        }

        return $url['path'] . '?' . http_build_query($params + $query); 
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>